package com.cysion.study.ui

import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.AddChooseTiListAdapter
import com.cysion.study.entity.AddChooseTiEntity
import com.cysion.study.entity.XitiListEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.targetfun._subscribe
import kotlinx.android.synthetic.main.activity_modify_choose_ti.*

//编辑练习题 单选  多选
class ModifyChooseTiActivity : BaseActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_modify_choose_ti
    private lateinit var dataAdapter: AddChooseTiListAdapter
    private val dataList: MutableList<AddChooseTiEntity> = mutableListOf()
    private var curPage = 1
    private var pageType = ""
    private var courseId = ""
    private var type = ""//1编辑，2新增
    private var obj: XitiListEntity? = null
    private var id=""
    override fun initView() {
        courseId = intent.extras.getString("courseId")
        pageType = intent.extras.getString("pageType")//pageType  1 单选，2多选
        type = intent.extras.getString("type")

        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            //1编辑，2新增
            if (type == "1") {
                setTitle("编辑选择题")
                obj = intent.extras.getSerializable("obj") as XitiListEntity?
            } else {
                setTitle("新增选择题")
            }
//            setTexts("添加", TopBar.Pos.RIGHT)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                } else if (pos == TopBar.Pos.RIGHT) {

                }
            }
        }

        tv_submit.setOnClickListener(this)
        tv_add.setOnClickListener(this)
        initRecyclerView()
        tb_class.setOnToggleChanged {
            println("###开关=" + it)
            isMone = it
            dataAdapter.setIsMore(it)

        }

    }

    private var isMone = false//是否多选

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        dataAdapter = AddChooseTiListAdapter(dataList, this)
        rv_list.adapter = dataAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        dataAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == AddChooseTiListAdapter.preview) {//删除
                if (dataList.size <= 1) {
                    ShowToast("至少保留一个答案选项")
                    return@setOnTypeClickListener
                }
                dataList.remove(dataList[position])
                dataAdapter.notifyDataSetChanged()
            } else if (flag == AddChooseTiListAdapter.agree) {
                if (!isMone) {
                    for (item in dataList) {
                        item.check = false
                    }
                    dataAdapter.notifyDataSetChanged()
                    println("###单选点击" + obj.content + "---" + obj.check)
                }
            }
        }
        //1编辑，2新增
        if (type == "1") {
            modify()
        } else {
            if (dataAdapter.itemCount == 0) {
//             var lists: MutableList<String> = mutableListOf("")
//             dataList.addAll(lists)
                var a = AddChooseTiEntity("", false)
                dataList.add(a)
                dataAdapter.notifyDataSetChanged()
            }
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_submit -> {
                for (obj in dataList) {
                    println("###" + obj.content + "---" + obj.check)
                }

                submit()

            }
            R.id.tv_add -> {
//                var lists: MutableList<AddChooseTiEntity> = mutableListOf()
                var a = AddChooseTiEntity("", false)
                dataList.add(a)
                dataAdapter.notifyDataSetChanged()
//                dataAdapter.notifyItemInserted(dataList.size-1)
            }
        }
    }


    private fun submit() {
        Alert.loading(self)
        var question = ""
        var answer = ""
        for (obj in dataList) {
            question += obj.content + "~~~"
        }
        for (obj in dataList) {
            if (obj.check) {
                if (isMone) {//多选
                    answer += obj.content + "@@@"
                } else {
                    answer = obj.content
                }
            }
        }
        if (TextUtils.isEmpty(answer)) {
            ShowToast("至少选择一个答案")
            return
        }
        var title = et_title.text.toString().trim()
        println("###答案=" + question)
        var type=""//类型：1、单选；2、多选
        if (isMone) {
            type = "2"
        } else {
            type = "1"
        }
        ApiClient.api.saveTi(id, courseId, question, answer, type, "1", "试题详解内容", title, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("保存成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }

    private fun modify() {
        id=obj?.id.toString()
        et_title.setText(obj?.title)
        val str = obj?.question
        val res = str?.split("~~~".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()
       /* for (i in res!!) {
            println("###=" + i)
            var a: AddChooseTiEntity? = null
            a?.content = i
            if (obj?.answer == i) {
                a?.check = true
            }
            if (a != null) {
                dataList.add(a)
            }
        }*/
        for (i in res!!) {
            var a = AddChooseTiEntity(i, false)
            dataList.add(a)
        }
        //pageType  1 单选，2多选
        if (pageType == "1") {
            tb_class.toggleOff()
        } else {
            tb_class.toggleOn()
        }

        dataAdapter.notifyDataSetChanged()
    }

    //adapter回调方法
    fun saveEditData(position: Int, str: String, checked: Boolean) {

        if (!isMone) {
            for (index in dataList.indices) {
                if (position == index) {
                    dataList[position].check = checked
                } else {
                    dataList[index].check = false
                }
                println(
                    "###条目外状态####$index---${dataList.get(index).content} ##状态=${dataList.get(
                        index
                    ).check}"
                )
            }
            dataAdapter.notifyDataSetChanged()
        }

    }

    private fun getDataList(page: Int, start: String, end: String) {
        Alert.loading(self)
        ApiClient.api.getTutorOrderList(UserCache.token, "", curPage.toString())
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()


                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }

    }


    override fun closeMvp() {
    }

}
